#pragma once

#include "Base_Https_Request.h"

#include <boost/beast/core.hpp>
#include <boost/json.hpp>
#include <boost/regex.hpp>

class Ai_Server : public Base_Https_Request<boost::beast::http::string_body>
{
    using BHR = Base_Https_Request<boost::beast::http::string_body>;

public:
    // 初始化
    Ai_Server(boost::asio::io_context& io_context, ssl::context& context, const std::string& server, const std::string& port)
        : BHR(io_context, context, server, port)
    {
        // 初始化http和json
        inithttp();
        initjson();
    }

    // 发送消息并更新json
    void send()
    {
        client.sendRequest(make_request());
    }

    // 发送消息并更新json
    void send(std::string str)
    {
        updatajson(str, "user");
        client.sendRequest(make_request());
    }

    // 接收回复
    std::string recv()
    {
        if (0)
        {
        resend: // 重发
            client.sendRequest(make_request());
        }
        std::string response = searchmessage(client.readResponse());
        if (response.size() == 0)
            goto resend; // 如果回复不安全，则重发
        updatajson(response, "assistant");
        return response;
    }

protected:
    boost::json::object json;

    // 初始化http
    void inithttp()
    {
        req.method(boost::beast::http::verb::post);
        // 设置目标路径
        req.target("/chat/completions");
        req.version(11);
        req.set(boost::beast::http::field::host, "api.deepseek.com");
        req.set(boost::beast::http::field::authorization, "Bearer sk-2a67a98fafe54623a2cee02f27ed9467");
        req.set(boost::beast::http::field::content_type, "application/json");
        req.set(boost::beast::http::field::content_length, std::to_string(boost::json::serialize(json).size()));
        req.set(boost::beast::http::field::connection, "keep-alive");
    }

    virtual void initjson()
    {
        boost::json::object o1;
        o1["content"] = "初始化一个assistant，应答用户的请求。";
        o1["role"] = "system";
        boost::json::object o2;
        o2["content"] = "Hi";
        o2["role"] = "user";
        boost::json::array ar;
        ar.push_back(o1);
        ar.push_back(o2);
        json["messages"] = ar;
        json["model"] = "deepseek-chat";
        json["frequency_penalty"] = 0;
        json["max_tokens"] = 2048;
        json["presence_penalty"] = 0;
        boost::json::object o3;
        o3["type"] = "text";
        json["response_format"] = o3;
        json["stop"];
        json["stream"] = false;
        json["stream_options"];
        json["temperature"] = 1;
        json["top_p"] = 1;
        json["tools"];
        json["tool_choice"] = "none";
        json["logprobs"] = false;
        json["top_logprobs"];
    }

    // 创建http请求并更新json的大小
    std::string make_request()
    {
        req.set(boost::beast::http::field::content_length, std::to_string(boost::json::serialize(json).size()));

        boost::beast::http::request_serializer<boost::beast::http::string_body> ser{ req };
        std::stringstream ss;
        ss << ser.get();

        std::string require;
        require += ss.str();
        require += boost::json::serialize(json);
        return require;
    }

    // 匹配httpclient返回的响应中的消息
    std::string searchmessage(std::string str)
    {
        boost::regex reg("\"content\":\\s*\"(.*?)\"");
        boost::smatch sm;
        boost::regex_search(str, sm, reg);
        std::stringstream ss;
        ss << sm[1];
        return sm[1].str();
    }

    // 更新json
    void updatajson(std::string str, std::string role)
    {
        boost::json::object o1;
        o1["content"] = str;
        o1["role"] = role;
        json["messages"].as_array().push_back(o1);
    }
};